package com.example.wms;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.example.classes.*;

/**
 * Activity for handling registration.
 * @author      Ankit Pasi, Alexander Huynh <a.huynh @ gatech.edu>
 */
public class registerActivity extends Activity
{
    private DataBase db;
    private boolean makeAdminMode;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        db = new DataBase(this);
        setContentView(R.layout.register_screen);
        Intent intent = getIntent();
        makeAdminMode = intent.getBooleanExtra("makeAdmin", false);
        if (makeAdminMode)
        {
            TextView banner = ((TextView)findViewById(R.id.registerScreenTitle));
            banner.setText("Register New Admin");
        }
    }

    /**
     * Registers a new Member with the inputted credentials.
     * @param view the content view
     */
    public void tryRegister(View view)
    {
        try
        {
            db.open();
        } catch(Exception e) {
            Log.v("WMS-DEBUG", "Error: " + e.toString());
        }

        String uname = ((EditText)findViewById(R.id.registerUserID)).getText().toString();
        Member dbentry=null;
        try{
            dbentry=db.getEntry(uname);
        }
        catch(Exception e)
        {
            Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
        }
        if (dbentry == null)
        {
            String upass = ((EditText)findViewById(R.id.registerPassword)).getText().toString();
            String confirm = ((EditText)findViewById(R.id.registerPassword2)).getText().toString();
            if (upass.equals(confirm))
            {
                upass = Encryptor.encrypt(upass);
                String email = ((EditText)findViewById(R.id.registerEmail)).getText().toString();
                Member mem;
                if (makeAdminMode)
                    mem = new Admin(uname, upass, email);
                else
                    mem = new User(uname, upass, email);
                db.createUserEntry(mem);
                db.close();
                Toast.makeText(this, "Registered " + uname + "!", Toast.LENGTH_LONG).show();
                finish();
            }
            else
            {
                Toast.makeText(this, "Passwords don't match!", Toast.LENGTH_LONG).show();
            }
        }
        else
        {
            Toast.makeText(this, "Username already exists!", Toast.LENGTH_LONG).show();
        }
    }
}